# coding=utf8
from bson import ObjectId
from wechat_sdk import WechatConf
from wechat_sdk import WechatBasic
import requests

from libs.help import content_to_imme
from models.user.info import model_user_info
from io import BytesIO


class WxInfo:
    def __init__(self, appid):
        accounts = model_user_info.coll.find_one({
            'WxAccounts': {
                '$elemMatch': {
                    'appid': appid
                }
            }
        })['WxAccounts']
        for account in accounts:
            if account['appid'] == appid:
                conf = WechatConf(
                    appid=account['appid'],
                    appsecret=account['appsecret']
                )
                self.wechat = WechatBasic(conf)
                self.name = account['remark']
                break

    def get_left(self):
        pass


def add_news_for_long(wechat, data):
    res = wechat.request.post(
        "https://api.weixin.qq.com/cgi-bin/material/add_news",
        data=data
    )
    return res['media_id']


def add_img_for_long(wechat, img_url):
    # 改成获取url
    img = requests.get(img_url)
    extion = img.headers['Content-Type']
    files = {
        'media': (str(ObjectId()) + content_to_imme(extion), BytesIO(img.content), extion)
    }
    res = wechat.request.post(
        "https://api.weixin.qq.com/cgi-bin/material/add_material",
        params={
            'type': 'image'
        },
        files=files
    )
    return res['media_id']


def get_resource(wechat, media_id):
    res = wechat.request.post(
        'https://api.weixin.qq.com/cgi-bin/material/get_material',
        data={"media_id": media_id}
    )
    return res


# todo 这个依然有错ing
def get_news_resource_list(wechat, offset, count):
    res = wechat.request.post(
        'https://api.weixin.qq.com/cgi-bin/material/get_material',
        data={"type": "news", 'offset': offset, 'count': count}
    )
    return res
